/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wisimconsole;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import wiBase.WiObject;
import wiBase.baseObject.Event;
import wiBase.baseObject.Node;
import wiBase.baseObject.Packet;

/**
 *
 * @author brother
 */
public class InfoPacketFrame extends javax.swing.JFrame {

    WiSimConsole console = null;
    ArrayList<WiObject> data = new ArrayList<>();

    /**
     * Creates new form InfoPacketFrame
     */
    public InfoPacketFrame(WiSimConsole console) {
	this.console = console;
	initComponents();
	
	doc = jtp_event.getDocument();
	setFont();
	jl_packets.setCellRenderer(new InfoPacketFrame.PacketListRenderer());
	try {
	    loadListPacket();
	} catch (NullPointerException ex) {
	}
	
	jl_packets.addMouseListener(new MouseAdapter() {
	    @Override
	    public void mouseClicked(MouseEvent event) {
		JList list = (JList) event.getSource();

		// Get index of item clicked

		int index = list.locationToIndex(event.getPoint());
		Object object = list.getModel().getElementAt(index);
		if (object instanceof Packet) {
		    refreshData((Packet) object);
		}
		// Repaint cell
		list.repaint(list.getCellBounds(index, index));
	    }
	});
    }
    
    private void refreshData(Packet packet) {
	
	lbl_id.setText("Id: " + packet.id);
	lbl_dest.setText("" + packet.destId + ":" + packet.destPort);
	lbl_source.setText("" + packet.sourceId + ":" + packet.sourcePort);
	lbl_type.setText("" + packet.type);
	lbl_size.setText(packet.size + "Byte");
	
	ArrayList<WiObject> lstDataEventOfPacket=null;
	System.gc();
	lstDataEventOfPacket = new ArrayList<>();
	
	lstDataEventOfPacket=console.getEngine().getPacketInfo(Integer.parseInt(packet.id));
	
	if(lstDataEventOfPacket!=null){
	    try {
		doc.remove(0, doc.getLength());
	    } catch (BadLocationException ex) {
		ex.printStackTrace();
		return;
	    }
	    for (WiObject object : lstDataEventOfPacket) {
		insertTextFormat(object);
	    }
	}
    }
    
    Document doc = null;
    EditorKit kit;
    ArrayList<WiObject> lstDataEventOfNode = new ArrayList<>();
    SimpleAttributeSet attDef = new SimpleAttributeSet();
    SimpleAttributeSet attType = new SimpleAttributeSet();
    SimpleAttributeSet attTime = new SimpleAttributeSet();
    SimpleAttributeSet attPacket = new SimpleAttributeSet();
    SimpleAttributeSet attNode = new SimpleAttributeSet();
    private void insertTextFormat(WiObject object) {
	if (object instanceof Event) {
	    try {
		doc.insertString(doc.getLength(), "Type:\t " + ((Event) object).type + "\n", attType);
		doc.insertString(doc.getLength(), "Time:\t " + ((Event) object).time + "\n", attTime);
		doc.insertString(doc.getLength(), "Packet Id:\t " + ((Event) object).packetId + "\n", attPacket);
		doc.insertString(doc.getLength(), "-----------Event Info----------" + "\n", attDef);
		doc.insertString(doc.getLength(), "Event: " + ((Event) object).toString() + "\n", attDef);

	    } catch (BadLocationException ex) {
	    }
	}

    }
    private void setFont() {
	int fontSizeDefault = 14;

	StyleConstants.setFontSize(attDef, fontSizeDefault);
	StyleConstants.setForeground(attDef, Color.black);

	StyleConstants.setFontSize(attType, fontSizeDefault);
	StyleConstants.setForeground(attType, Color.green);

	StyleConstants.setFontSize(attTime, fontSizeDefault);
	StyleConstants.setForeground(attTime, Color.blue);

	StyleConstants.setFontSize(attPacket, fontSizeDefault);
	StyleConstants.setForeground(attPacket, Color.black);

	StyleConstants.setFontSize(attNode, fontSizeDefault);
	StyleConstants.setForeground(attNode, Color.blue);
    }
    @Override
    public void setVisible(boolean b) {
	super.setVisible(b);
	if (b) {
	    loadListPacket();
	}
    }
    
    private void loadListPacket() throws NullPointerException {
	data = console.getEngine().getListPackets();
	jl_packets.setListData(data.toArray());
    }
    
    class PacketListRenderer extends JLabel implements ListCellRenderer {
	
	@Override
	public Component getListCellRendererComponent(
		JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
	    setEnabled(list.isEnabled());
	    setOpaque(isSelected);
	    setFont(list.getFont());
	    setBackground(list.getBackground());
	    setForeground(list.getForeground());
	    if (isSelected && cellHasFocus) {
		setBackground(Color.YELLOW);
		setForeground(Color.RED);
		if(value instanceof Packet) {
		    //refreshData((Packet)value);
		}
	    }
	    if (value instanceof Packet) {
		Packet packet = (Packet) value;
		setText("id: " + packet.id);
	    } else {
		setText("unknow");
	    }
	    
	    return this;
	}
    }

    // Do not Edit Here!!!
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jl_packets = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtp_event = new javax.swing.JTextPane();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lbl_color = new javax.swing.JLabel();
        lbl_type = new javax.swing.JLabel();
        lbl_size = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        lbl_id = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lbl_width = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        lbl_height = new javax.swing.JLabel();
        lbl_source = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lbl_dest = new javax.swing.JLabel();
        btn_ok = new javax.swing.JButton();

        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(552, 415));

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder("Packet"));

        jl_packets.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jl_packets);

        jtp_event.setBorder(javax.swing.BorderFactory.createTitledBorder("Event Relate to Node"));
        jtp_event.setText("Event id=0 type=send source-id=1");
        jtp_event.setOpaque(false);
        jScrollPane1.setViewportView(jtp_event);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Packet:");

        lbl_color.setText("Red");

        lbl_type.setText("message");

        lbl_size.setText("32Bit");

        jLabel3.setText("Size:");

        jLabel7.setText("Dest Id/Port:");

        lbl_id.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lbl_id.setText("id=1");

        jLabel13.setText("Height:");

        jLabel2.setText("Color:");

        lbl_width.setText("20px");

        jLabel11.setText("Width:");

        lbl_height.setText("20px");

        lbl_source.setText("43:255");

        jLabel4.setText("Type:");

        jLabel6.setText("Source Id/Port:");

        lbl_dest.setText("-1:255");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(lbl_id))
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel6)
                    .add(jLabel4)
                    .add(jLabel7)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(lbl_size)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jPanel2Layout.createSequentialGroup()
                                .add(lbl_dest)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(jLabel13))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                                .add(lbl_source)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(jLabel11))
                            .add(jPanel2Layout.createSequentialGroup()
                                .add(lbl_type)
                                .add(94, 94, 94)
                                .add(jLabel2)))
                        .add(18, 18, 18)
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lbl_height)
                            .add(lbl_color)
                            .add(lbl_width)))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel7)
                        .add(lbl_dest))
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(lbl_id))
                        .add(18, 18, 18)
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel4)
                            .add(lbl_type)
                            .add(jLabel2)
                            .add(lbl_color))
                        .add(18, 18, 18)
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel6)
                            .add(lbl_source)
                            .add(jLabel11)
                            .add(lbl_width))
                        .add(18, 18, 18)
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel13)
                            .add(lbl_height))))
                .add(18, 18, 18)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(lbl_size)))
        );

        btn_ok.setText("OK");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(0, 93, Short.MAX_VALUE))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(btn_ok, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 69, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(btn_ok))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 155, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
	/* Set the Nimbus look and feel */
	//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
	 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
	 */
	try {
	    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
		if ("Nimbus".equals(info.getName())) {
		    javax.swing.UIManager.setLookAndFeel(info.getClassName());
		    break;
		}
	    }
	} catch (ClassNotFoundException ex) {
	    java.util.logging.Logger.getLogger(InfoPacketFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (InstantiationException ex) {
	    java.util.logging.Logger.getLogger(InfoPacketFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (IllegalAccessException ex) {
	    java.util.logging.Logger.getLogger(InfoPacketFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (javax.swing.UnsupportedLookAndFeelException ex) {
	    java.util.logging.Logger.getLogger(InfoPacketFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	}
	//</editor-fold>

	/* Create and display the form */
	java.awt.EventQueue.invokeLater(new Runnable() {
	    public void run() {
		//new InfoPacketFrame().setVisible(true);
	    }
	});
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_ok;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList jl_packets;
    private javax.swing.JTextPane jtp_event;
    private javax.swing.JLabel lbl_color;
    private javax.swing.JLabel lbl_dest;
    private javax.swing.JLabel lbl_height;
    private javax.swing.JLabel lbl_id;
    private javax.swing.JLabel lbl_size;
    private javax.swing.JLabel lbl_source;
    private javax.swing.JLabel lbl_type;
    private javax.swing.JLabel lbl_width;
    // End of variables declaration//GEN-END:variables
}
